<template>
  <div class="container">
    <a-row :gutter="20">
      <a-col :span="4">
        <a-tree ref="orgTreeRef" :fieldNames="{ key: 'id',title: 'label'}" :data="state.treeData" @select="treeClick"></a-tree>
      </a-col>
      <a-col :span="20">
        <a-button type="primary" @click="addOrg">
          <template #icon><icon-plus-circle /></template>添加下级组织
        </a-button>
        <table class="mytable">
          <tr>
            <th style="width: 15%">组织名称</th>
            <th>{{state.activeTreeNode.label}}</th>
            <th style="width: 15%">
              <a-button size="mini" type="primary" @click="editOrg(state.activeTreeNode.id)">修改</a-button>
            </th>
          </tr>
        </table>
      </a-col>
    </a-row>

    <a-modal :title="state.popupTitle" v-model:visible="state.entityDetailVisible" :footer="false">
      <OrgDetail v-if="state.entityDetailVisible" v-model="state.entityDetailVisible" :entityId="state.popupEntityId" :pid="state.activeTreeNode.id"></OrgDetail>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import mittBus from "@/utils/route-listener"
import {reactive, ref, onMounted, onUnmounted, defineAsyncComponent, nextTick} from "vue";
// 引入组件
const OrgDetail = defineAsyncComponent(() => import('@/views/sys/org/orgDetail.vue'));

// 定义dom
const orgTreeRef = ref(null);
const state = reactive({
  treeData : [],
  activeTreeNode : {},

  entityDetailVisible : false,
  popupTitle : '',
  popupEntityId : 0,
})
const loadOrgTree = () =>{
  axios.post('/sys/org/orgtreedata', {orgId : 1}).then( (res) =>{
    const { data } = res
    state.treeData = data
    if(state.treeData.length > 0){
      state.activeTreeNode = state.treeData[0]
      nextTick(()=>{
        orgTreeRef.value.selectNode("1")
        orgTreeRef.value.expandAll()
      })
    }
  })
}
const treeClick = (newSelectedKeys, event)=>{
  state.activeTreeNode = event.node
}
const addOrg = ()=>{
  state.popupEntityId = 0;
  state.popupTitle= "新增组织"
  state.entityDetailVisible= true
}
const editOrg = (id)=>{
  state.popupEntityId = id;
  state.popupTitle= "修改组织"
  state.entityDetailVisible= true
}
onMounted(()=>{
  loadOrgTree();
  mittBus.on("orgchange", ()=>{
    loadOrgTree();
  })
})
onUnmounted(()=>{
  mittBus.off("orgchange", ()=>{})
})

</script>

<style scoped>

</style>
